<?php

/**
 * Ignus Framework
 *
 * @author Sergey Palyanov <sergey.palyanov@gmail.com>
 * @link http://code.google.com/p/ignus-php/
 * @license http://apache.org/licenses/LICENSE-2.0
 * @package Ignus
 * @subpackage App
 * @since 0.1
 */

namespace Ignus;

use \Ignus\View\Environment;
use \Ignus\View\Extension\Integrate;
use \Ignus\View\Loader\FileLoader;

/**
 * @package Ignus
 * @subpackage App
 * @since 0.5.8
 */
class View
{
    /**
     * @var \Ignus\View\Environment
     * @since 0.7.0
     */
    private static $env = null;

    /**
     * @var \Ignus\View\Template
     * @since 0.7.0
     */
    private $template;

    /**
     * Prepares template
     * @param string $template Path to template
     * @throws \RuntimeException if template file doesn't exists
     */
    public function __construct($template)
    {
        if (self::$env == null) {
            $production = App::isProduction();
            $options = array(
                'cache'     =>  $production ? App::getAppDir('data') : false,
                'debug'     =>  !$production,
            );
            self::$env = new Environment(new FileLoader(App::getAppDir('views')), $options);
            self::$env->addExtension(new Integrate());
        }

        $this->template = self::$env->loadTemplate($template);
    }

    /**
     * Renders and returns template with specified name
     * @param array $vars Template variables
     * @return string Template parse result
     */
    public function parse(array $vars = array())
    {
        $vars += $this->getImplicitVars();
        return $this->template->render($vars);
    }

    /**
     * Parse template to output
     * @param array $vars Template variables
     * @return void
     */
    public function display(array $vars = array())
    {
        echo $this->parse($vars);
    }

    private function getImplicitVars()
    {
        return array(
            'ignus'     =>  array(
                'dev'       =>  !App::isProduction(),
            ),
            'cookies'   =>  $_COOKIE,
        );
    }
}
